package com.socket.nio.nio.pipeline;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author Hexudong
 * @date 2025/4/12
 */
@Slf4j
public class EventLoopClient {
  public static void main(String[] args) {
    ChannelFuture channelFuture = new Bootstrap()
        .group(new NioEventLoopGroup())
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<NioSocketChannel>() {
          @Override
          protected void initChannel(NioSocketChannel ch) {
            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
            ch.pipeline().addLast(new StringEncoder());
          }
        })
        .connect(new InetSocketAddress("localhost", 8082));

    Channel channel = channelFuture.channel();
    log.debug("channel = {}", channel.getClass());

    new Thread(() -> {
      Scanner scanner = new Scanner(System.in);
      while (true) {
        String line = scanner.nextLine();
        if ("q".equals(line)) {
          channel.close();
          break;
        }
        channel.writeAndFlush(line);
      }
    }).start();
  }
}
